<?

class User extends BDS {

    private static $salt = "_salt";
    private $user = false;
    protected static $tablename = "users__settings";

    public function __construct() {
        if (empty($_SESSION['UID'])) {
            $_SESSION['UID'] = 0;
        }
        $this->user = $this->GetUser();
    }

    public function GetUser($id = false) {
        $id = $id ? $id : $_SESSION['UID'];
        $process = $GLOBALS['MAIN']->DB->select()->fields()->table('users__settings')->cond('id', $id)->exec();
        $user = $process->fetch();
        return $user;
    }

    public function isAdmin($id = false) {
        $id = $id ? $id : $_SESSION['UID'];
        return $this->isAuth($id) && $this->user['group_id'] == 1;
    }

    public function isAuth($id = false) {
        $id = $id ? $id : $_SESSION['UID'];
        $process = $GLOBALS['MAIN']->DB->select()->fields('id')->table('users__settings')->cond('id', $id)->cond('is_auth', Y)->exec();
        return $process->fetch() == true;
    }

    public function Login($login, $pass) {
        $pass = md5($pass . self::$salt);
        BDS::Init();
        $ok = User::UpdateList(array('login' => $login, 'pass_hash' => $pass), array('is_auth' => Y));
        if ($ok) {
            $data = User::GetList(array('login' => $login, 'pass_hash' => $pass), array(), array('id'))->fetch();
            $id = $data['id'];
            $_SESSION['UID'] = $id;
        }
        return $ok;
    }

    public function Logout($id = false) {
        $id = $id ? $id : $_SESSION['UID'];
        BDS::Init();
        $result = User::Update($id, array('is_auth' => N));
        $_SESSION['UID'] = 0;
        return $result;
    }

    function GetUserInfo($id = false) {
        $id = $id ? $id : $_SESSION['UID'];
        $user = $this->GetUser($id);
        if ($user) {
            BDS::Init('users__groups');
            $group = BDS::GetList(array('id' => $user['group_id']));
            $user['group'] = $group->fetch();
            BDS::Init('users__fields');
            $fieldsObj = BDS::GetList(array('group_id' => $user['group_id'], DB_LOGIC_OR.":group_id" => DB_COND_IS.":".N));
            while ($field = $fieldsObj->fetch()) {
                BDS::Init('users__values');
                $value = BDS::GetList(array('user_id' => $id, 'field_id' => $field['id']))->fetch();
                $field['value_id'] = $value['id'];
                $field['value'] = $value['value'];
                $user['fields'][$field['code']] = $field;
            }
        }
        return $user;
    }

}
